#include "CTabCtrl.h"

CTabCtrl::CTabCtrl(HINSTANCE hInstance, HWND hTabCtrl)
{
	m_hInstance		= hInstance	;
	m_hTabCtrl		= hTabCtrl	;
	m_hImageList	= ImageList_Create(16, 16, ILC_COLOR32 | ILC_MASK, 0, 10);
}

BOOL CTabCtrl::CreateTabPage(LPTABPAGE lptp)
{
	BOOL		bRet	=	 FALSE	;
	TC_ITEM		tci					;
	int			nRet				,
				nItem				;

	if(NULL != lptp)
	{
		lptp->hWndTabPage = CreateDialog(m_hInstance, MAKEINTRESOURCE(lptp->wDialogID), 
											GetParent(m_hTabCtrl), lptp->lpfnDlgProc);

		if(NULL != lptp->hWndTabPage) {
			tci.mask	= TCIF_TEXT;

			if(NULL != lptp->hIcon) {
				tci.mask |= TCIF_IMAGE;
				nRet = ImageList_AddIcon(m_hImageList, lptp->hIcon);

				TabCtrl_SetImageList(m_hTabCtrl, m_hImageList);

				tci.iImage = nRet;
			}

			tci.pszText		= lptp->lpszText;

			nItem = TabCtrl_GetItemCount(m_hTabCtrl);

			TabCtrl_InsertItem(m_hTabCtrl, nItem, &tci);

			m_TabPages.push_back(lptp);

			if(!nItem)
				ShowTabPage(nItem);

			bRet = TRUE;
		}
	}

	return bRet;
}

void CTabCtrl::ShowTabPage(int nPage)
{
	std::vector<LPTABPAGE>::iterator	iter			;
	int									n		= 0		;
	RECT								rc		= {0}	,
										rcItem	= {0}	;
	POINT								pt		= {0}	;
	for(iter = m_TabPages.begin();
		iter != m_TabPages.end();
		++iter) {

		if(n == nPage) {
			GetWindowRect(m_hTabCtrl, &rc);
			pt.x = rc.left;
			pt.y = rc.top;
			ScreenToClient(GetParent(m_hTabCtrl), &pt);
			TabCtrl_GetItemRect(m_hTabCtrl, 0, &rcItem);

			MoveWindow((*iter)->hWndTabPage, pt.x + 4, pt.y + (rcItem.bottom - rcItem.top) + 4,
				(rc.right-rc.left) - 8, ((rc.bottom-rc.top) - pt.y) , TRUE);

			ShowWindow((*iter)->hWndTabPage, SW_SHOW);
			BringWindowToTop((*iter)->hWndTabPage);
			UpdateWindow((*iter)->hWndTabPage);
			TabCtrl_SetCurSel(m_hTabCtrl, n);
		} else {
			ShowWindow((*iter)->hWndTabPage, SW_HIDE);
		}

		++n;
	}
}

void CTabCtrl::ClearTabCtrl(void)
{
	std::vector<LPTABPAGE>::iterator	iter	;

	TabCtrl_DeleteAllItems(m_hTabCtrl);

	for(iter = m_TabPages.begin();
		iter != m_TabPages.end();
		++iter) {
		if(NULL != (*iter)->lpszText)
			free((*iter)->lpszText);
		if(IsWindow((*iter)->hWndTabPage))
			DestroyWindow((*iter)->hWndTabPage);
		delete *iter;
	}

	m_TabPages.clear();
}

BOOL CTabCtrl::OnNotify(LPARAM lParam)
{
	LPNMHDR lpnmhdr = (LPNMHDR)lParam	;
	int		nPage						;

	switch(lpnmhdr->code) {
	case TCN_SELCHANGING:
		return FALSE;
	case TCN_SELCHANGE:
		nPage = TabCtrl_GetCurSel(m_hTabCtrl);
		ShowTabPage(nPage);
		return TRUE;
	}
	return FALSE;
}

CTabCtrl::~CTabCtrl()
{
	ClearTabCtrl();
}
